<?php

namespace App\Services\Square;

use App\Models\Square\Feeds;
use App\Models\Square\FeedViewByUser;
use App\Models\Square\FeedViewBySchool;
use App\Models\Square\FeedsTags;

use App\Models\Member\Like;
use App\Models\Member\Comment;
use App\Models\Member\Friend;
use App\Models\Member\HubSettings;
use App\Models\Member\Tag;
use App\Models\Member\TagMember;

use App\Models\Store\Store;
use App\Models\News\News;
use App\Models\Activity\Activity;
use App\Models\Common\City;
use App\Models\Common\Statistics;
use App\Models\Common\File;

use App\Services\Com\ProcessService;
use App\Services\Com\StatisticsService;
use App\Services\Member\MemberService;
use App\Services\Member\LikeService;
use App\Services\Member\MemberInfoService;
use App\Services\Activity\ActivityService;
use App\Services\Square\FeedsService;
use App\Services\Vote\VoteService;
use App\Services\Talking\TalkingService;

use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use AlibabaCloud\Vod\Vod;

use App\Services\Com\UtilService;

use App\Jobs\NotifyUsers;
use App\Jobs\FeedDispatch;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

class FeedsService
{
    /**
     * tag返回 uuid 
     * @param array tag_title 
     * @return 
     **/
    public static function tagObjRes(array $tag_titles = []){
        $title_list = [];
        if(!empty($tag_titles)){
            $list = FeedsTags::whereIn('title', $tag_titles)->where('state', 1)->get()->toArray();
            $title_list  = array_column($list,null,'title');
        }
        return $title_list;
    }

    /**
     * feed判断文件处理
     * @param file_type 文件类型
     * @param file_list 文件列表
     * @return [['coverURL'=>'','playURL'=>'']]
     **/
    public static function feedFile($file_type = '', $file_list = null){

        $file_list_res = null;
        if(empty($file_list)){
            return $file_list_res;
        }

        $cache_key = config('cache.key_list.feed_file').md5($file_type).md5($file_list);
        $cache_data = Cache::get($cache_key);
        if(!empty($cache_data)){
            // return $cache_data;
        }

        //设置全局客户端
        AlibabaCloud::accessKeyClient(config('aliyun.aliyunvideo.accessKeyId'), config('aliyun.aliyunvideo.accessKeySecret'))
            ->regionId(config('aliyun.aliyunvideo.regionId'))
            ->asDefaultClient();
        
        if($file_type == 'video'){
            $file_list = json_decode($file_list, true);
            try {
                $vdo_id = '';
                if(isset($file_list[0]['path'])){
                    $vdo_id = $file_list[0]['path'];
                }elseif(isset($file_list[0])){
                    $vdo_id = $file_list[0];
                }
                
                $request = Vod::v20170321()->getPlayInfo();
                $result = $request->withVideoId($vdo_id)->debug(false)->request();
                $video_arr = $result->toArray();
                if(empty($vdo_id) || !isset($video_arr['VideoBase']['CoverURL'])){
                   Log::alert('aliyun vdo_id'.$file_list); 
                }
                $f_list = [
                    'coverURL' => $video_arr['VideoBase']['CoverURL'] ?? '',
                    'playURL' => $video_arr['PlayInfoList']['PlayInfo'][0]['PlayURL'] ?? '',
                ];
                $file_list_res = [$f_list];
            } catch (ServerException $e) {
                $file_list_res = null;
                Log::alert('aliyun err'.var_export($e->getMessage(), true));
            }
        }else{
            $f_list = null;
            $file_list = json_decode($file_list, true);

            if(!empty($file_list)){
                foreach ($file_list as $key => $i_value) {
                    if(is_array($i_value) && isset($i_value['path'])){//有图片宽高信息
                        $f_list[] = [
                            'coverURL' => UtilService::coverURL($i_value['path']),
                            'playURL' => $i_value['path'],
                            'height' => $i_value['height'],
                            'width' => $i_value['width'],
                        ];
                    }elseif(!is_array($i_value)){//开始没有图片宽高信息
                        $f_list[] = [
                            'coverURL' => UtilService::coverURL($i_value),
                            'playURL' => $i_value
                        ];    
                    }
                    
                }
            }
            $file_list_res = $f_list;
        }

        Cache::put($cache_key, $file_list_res, config('cache.ttl_cfg'));
        return $file_list_res;
    }

    /**
     * 权限检测
     * 1关闭+Talking&关闭评论，2关闭+Talking&允许评论，3允许+Talking&关闭评论，4允许+Talking&评论 
     * @param type 类型： talking(+talking), comment(评论)
     * @param param 业务参数 service_uuid feed信息流uuid
     * return ['status'=>true, 'msg'=>'权限正常']
     **/
    public static function checkPerm(string $type = '', array $param = []){
        
        $fees = self::detail($param['service_uuid']);
        $res = [
            'status'=>true,
            'msg'=>'ok',
        ];
        if(!empty($fees)){
            $feed_arr = $fees->toArray();

            if($type == 'talking'){
                if($feed_arr['permission'] == 1){
                    $res = [
                        'status'=>false,
                        'msg'=>'关闭+Talking&关闭评论',
                    ];
                }
                if($feed_arr['permission'] == 2){
                    $res = [
                        'status'=>false,
                        'msg'=>'关闭+Talking&允许评论',
                    ];
                }
            }

            if($type == 'comment'){
                if($feed_arr['permission'] == 1){
                    $res = [
                        'status'=>false,
                        'msg'=>'关闭+Talking&关闭评论',
                    ];
                }
                if($feed_arr['permission'] == 3){
                    $res = [
                        'status'=>false,
                        'msg'=>'允许+Talking&关闭评论',
                    ];
                }
            }
            
        }
        return $res;
    }

    public static function feedDel(array $param = []){
        $del_res = false; 
        $del_res1 = false; 
        $del_res2 = false;

        try {
            DB::beginTransaction();
            $where[] = ['uuid', '=', $param['feed_uuid']];
            $where[] = ['member_uuid', '=', $param['member_uuid']];

            $res = Feeds::where($where)->first();
            $where_by_user_owner[] = ['post_uuid', '=', $param['feed_uuid']];
            $res_by_user = FeedViewByUser::where($where_by_user_owner)->first();
            
            //如果是所有者 删除全部
            if(!empty($res)){
                $del_res1 = Feeds::where($where)->delete();
                $del_res2 = FeedViewByUser::where($where_by_user_owner)->delete();
                $del_res = FeedViewBySchool::where($where_by_user_owner)->delete();
            }else {
                if(!empty($res_by_user)){ //圈子里有
                    $where_by_user_singel[] = ['post_uuid', '=', $param['feed_uuid']];
                    $where_by_user_singel[] = ['member_uuid', '=', $param['member_uuid']];
                    $del_res = FeedViewByUser::where($where_by_user_singel)->delete();
                }
                //学校里有
                $where_by_user_owner_school[] = ['post_uuid', '=', $param['feed_uuid']];
                $res_by_school = FeedViewBySchool::where($where_by_user_owner_school)->first();
                if(!empty($res_by_school)){ 
                    $where_by_user_singel_school[] = ['post_uuid', '=', $param['feed_uuid']];
                    $where_by_user_singel_school[] = ['form_member_uuid', '=', $param['member_uuid']];
                    $del_res = FeedViewBySchool::where($where_by_user_singel_school)->delete();
                }   
            }
            

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            throw new \Exception($e->getLine().$e->getMessage());
        }

        return [$del_res1, $del_res2, $del_res];
    }

    /**
     * 返回某条feed
     * 
     **/
    public static function detail($uuid){

        $res = Feeds::where('uuid', $uuid)->first();
        return $res ? $res : null;
    }

    public static function detailStruct($value = null, $member_uuid = ''){
        if(empty($value)){
            //不存在就认为 被删除的
            return self::detailDelStruct($value, $member_uuid);
        }

        $cache_key = config('cache.key_list.feed_file').md5($value->file_list).md5($value->file_type);
        $cache_data = Cache::get($cache_key);
        if(!empty($cache_data)){
            $file_list = $cache_data;
        }else{
            //获取上传的文件
            if(isset($value->file_type) && $value->file_type == 'video'){
                //设置全局客户端
                AlibabaCloud::accessKeyClient(config('aliyun.aliyunvideo.accessKeyId'), config('aliyun.aliyunvideo.accessKeySecret'))
                    ->regionId(config('aliyun.aliyunvideo.regionId'))
                    ->asDefaultClient();

                $request = Vod::v20170321()->getPlayInfo();

                $file_list = json_decode($value->file_list);
                $vdo_id = '';
                if(isset($file_list[0]['path'])){
                    $vdo_id = $file_list[0]['path'];
                }elseif(isset($file_list[0])){
                    $vdo_id = $file_list[0];
                }
                $result = $request->withVideoId($vdo_id)->debug(false)->request();
                $video_arr = $result->toArray();

                $f_list = [
                    'coverURL' => $video_arr['VideoBase']['CoverURL'] ?? '',
                    'playURL' => $video_arr['PlayInfoList']['PlayInfo'][0]['PlayURL'] ?? '',
                ];
                $file_list = [$f_list];
            }elseif(isset($value->file_list)){
                $f_list = [];
                $file_list = json_decode($value->file_list, true);
                if(!empty($file_list)){
                    foreach ($file_list as $key => $i_value) {
                        if(is_array($i_value)){//有图片宽高信息
                            $f_list[] = [
                                'coverURL' => UtilService::coverURL($i_value['path']),
                                'playURL' => $i_value['path'],
                                'height' => $i_value['height'],
                                'width' => $i_value['width'],
                            ];
                        }else{//开始没有图片宽高信息
                            $f_list[] = [
                                'coverURL' => UtilService::coverURL($i_value),
                                'playURL' => $i_value
                            ];
                        }

                    }
                }
                $file_list = $f_list;
            }
            Cache::put($cache_key, $file_list, config('cache.ttl_cfg'));
        }

        $city_arr = City::getCityById($value->place_city_code);
        $path_names_arr = null;
        if(!empty($city_arr)){
            $path_names_arr = explode('/', $city_arr['path_names']);
        }

        //转发的推文
        $retweet_info = null;
        if(!empty($value->retweet_uuid)){ //转发的feed

            $fun = $value->retweet_type;
            $retweet_info = [ //转发原文
                'info_type'=>$value->retweet_type,//feed 信息流水feed或者 block里面的结构： 活动activity talking vote投票
                $value->retweet_type=>!empty($value->retweet_uuid) ? self::$fun($value->retweet_uuid, $member_uuid) : null,
            ];
        }
        $comment_cnt = StatisticsService::get($value->uuid)['comment_num'];
        $user_info_online[] = $user_info = MemberInfoService::userInfoByUuid($value->member_uuid, $member_uuid);
        //用户在线判断
        if(!empty($user_info_online)){
            $user_info_online_uuids = array_column($user_info_online, 'uuid');
            $user_onlines = MemberService::onlineUsersMtl($user_info_online_uuids);

            if(!empty($user_info)){
                if(isset($user_onlines[$user_info['uuid']])){
                    $user_info['online'] = 1;
                }
            }
        }

        //取收藏的信息流
        $collect_arr = MemberService::collectByMemberUuids([$value->uuid], 5, $member_uuid);

        $feed_uuids = [];
        $tag_title_list = [];
        $tag_titles = [];
        // foreach ($row['data'] as $key => $value) {
        $feed_uuids[] = $value->uuid;
        $tag_arr = json_decode($value->tags);
        if(!empty($tag_arr)){
            foreach ($tag_arr as $tag_key => $tag_value) {
                $tag_titles[] = $tag_value;
            }
        }
        // }
        $tag_title_list = FeedsService::tagObjRes($tag_titles);

        //标签全部结构
        $tag_struct_obj = null;
        if(!empty($value->tags)){
            $feed_tags_arr = json_decode($value->tags);
            foreach ($feed_tags_arr as $f_t_a_key => $f_t_a_value) {
                if(isset($tag_title_list[$f_t_a_value])){
                    $tag_struct_obj[] = $tag_title_list[$f_t_a_value];
                }
            }
        }

        $data = [
            'user'=> $user_info,
            'info'=>[
                'id'=>$value->id,//信息id
                'uuid'=>$value->uuid,//信息uuid
                'ad'=>0,//1是0不是
                'type'=>$value->retweet_uuid ? 'retweet' : 'feed',//retweet转发 feed非转发
                'add_time'=>$value->created_at,//发布时间
                'detail'=>$value->content,//内容文字 @人格式：@赵灵儿@
                'file_list'=>$file_list,//一个资源列表
                'file_type'=>$value->file_type,//video 视频或者video 图片
                'comment_count'=>(int)$comment_cnt,//评论量

                'notify_users_nick'=>$value->notify_users_nick,//@人昵称
                'notify_users'=>$value->notify_users,//@人uuid

                'like_count'=>LikeService::sumLike(5, $value->uuid),//300点赞
                'has_like'=>LikeService::hasLike($member_uuid, 5, $value->uuid),//1是已经点like 0是未点like
                'has_collect'=>isset($collect_arr[$value->uuid]) ? 1 : 0,//1是已经收藏 0是未

                'longitude'=>$value->longitude,
                'latitude'=>$value->latitude,
                'place_city_code'=>$value->place_city_code,//城市code
                'place'=>$value->place,//位置名
                'place_address'=>$value->place_address,//位置详细
                'place_level_1' => $path_names_arr[0] ?? null, //省
                'place_level_2' => $path_names_arr[1] ?? null, //市
                'place_level_3' => $path_names_arr[2] ?? null, //区
                'place_city_name' => $city_arr['name'] ?? null,//城市code

                'permission'=>$value->permission,// 1关闭+Talking&允许评论，2允许+Talking&关闭评论，3允许+Talking&评论',

                'tag_struct_obj'=> $tag_struct_obj,
                'tag_struct'=> !empty($value->tags) ? json_decode($value->tags) : null,
                'retweet_comment'=>!empty($value->retweet_comment) ? json_decode($value->retweet_comment) : null,
                'retweet_info'=>$retweet_info,
            ]
        ];
        return $data;
    }

    /**
     * 返回某条feed定义结构
     * 
     **/
    public static function postDetail($value = null, $member_uuid = '', $user=null){
        if(empty($value)){
            //不存在就认为 被删除的
            return self::detailDelStruct($value, $member_uuid);
        }

        $cache_key = config('cache.key_list.feed_file').md5($value->file_list).md5($value->file_type);
        $cache_data = Cache::get($cache_key);
        if(!empty($cache_data)){
            $file_list = $cache_data;
        }else{
            //获取上传的文件
            if(isset($value->file_type) && $value->file_type == 'video'){
                //设置全局客户端
                AlibabaCloud::accessKeyClient(config('aliyun.aliyunvideo.accessKeyId'), config('aliyun.aliyunvideo.accessKeySecret'))
                    ->regionId(config('aliyun.aliyunvideo.regionId'))
                    ->asDefaultClient();

                $request = Vod::v20170321()->getPlayInfo();

                $file_list = json_decode($value->file_list);
                $vdo_id = '';
                if(isset($file_list[0]['path'])){
                    $vdo_id = $file_list[0]['path'];
                }elseif(isset($file_list[0])){
                    $vdo_id = $file_list[0];
                }
                $result = $request->withVideoId($vdo_id)->debug(false)->request();
                $video_arr = $result->toArray();
                
                $f_list = [
                    'coverURL' => $video_arr['VideoBase']['CoverURL'] ?? '',
                    'playURL' => $video_arr['PlayInfoList']['PlayInfo'][0]['PlayURL'] ?? '',
                ];
                $file_list = [$f_list];
            }elseif(isset($value->file_list)){
                $f_list = [];
                $file_list = json_decode($value->file_list, true);
                if(!empty($file_list)){
                    foreach ($file_list as $key => $i_value) {
                        if(is_array($i_value)){//有图片宽高信息
                            $f_list[] = [
                                'coverURL' => UtilService::coverURL($i_value['path']),
                                'playURL' => $i_value['path'],
                                'height' => $i_value['height'],
                                'width' => $i_value['width'],
                            ];
                        }else{//开始没有图片宽高信息
                            $f_list[] = [
                                'coverURL' => UtilService::coverURL($i_value),
                                'playURL' => $i_value
                            ];    
                        }
                        
                    }
                }
                $file_list = $f_list;
            }
            Cache::put($cache_key, $file_list, config('cache.ttl_cfg'));
        }

        $city_arr = City::getCityById($value->place_city_code);
        $path_names_arr = null;
        if(!empty($city_arr)){
            $path_names_arr = explode('/', $city_arr['path_names']);
        }
        
        //转发的推文
        $retweet_info = null;
        if(!empty($value->retweet_uuid)){ //转发的feed

            $fun = $value->retweet_type;
            $retweet_info = [ //转发原文
                            'info_type'=>$value->retweet_type,//feed 信息流水feed或者 block里面的结构： 活动activity talking vote投票
                            $value->retweet_type=>!empty($value->retweet_uuid) ? self::$fun($value->retweet_uuid, $member_uuid) : null,
                        ];
        }   
        $comment_cnt = StatisticsService::get($value->uuid)['comment_num'];

        //取收藏的信息流
        $collect_arr = MemberService::collectByMemberUuids([$value->uuid], 5, $member_uuid);

        $feed_uuids = [];
        $tag_title_list = [];
        $tag_titles = [];
        // foreach ($row['data'] as $key => $value) {
            $feed_uuids[] = $value->uuid;
            $tag_arr = json_decode($value->tags);
            if(!empty($tag_arr)){
                foreach ($tag_arr as $tag_key => $tag_value) {
                    $tag_titles[] = $tag_value;
                }
            }
        // }
        $tag_title_list = FeedsService::tagObjRes($tag_titles);

        //标签全部结构
        $tag_struct_obj = null;
        if(!empty($value->tags)){
            $feed_tags_arr = json_decode($value->tags);
            foreach ($feed_tags_arr as $f_t_a_key => $f_t_a_value) {
                if(isset($tag_title_list[$f_t_a_value])){
                    $tag_struct_obj[] = $tag_title_list[$f_t_a_value];
                }
            }
        }

        $data = [
                'user'=> [
                    'uuid' => $user['uuid'],
                    'avatar' => $user['avatar_url'],
                ],
                'info'=>[
                    'id'=>$value->id,//信息id
                    'uuid'=>$value->uuid,//信息uuid
                    'ad'=>0,//1是0不是
                    'type'=>$value->retweet_uuid ? 'retweet' : 'feed',//retweet转发 feed非转发
                    'add_time'=>$value->created_at,//发布时间
                    'detail'=>$value->content,//内容文字 @人格式：@赵灵儿@
                    'file_list'=>$file_list,//一个资源列表
                    'file_type'=>$value->file_type,//video 视频或者video 图片
                    'comment_count'=>(int)$comment_cnt,//评论量

                    'notify_users_nick'=>$value->notify_users_nick,//@人昵称
                    'notify_users'=>$value->notify_users,//@人uuid
                    
                    'like_count'=>LikeService::sumLike(5, $value->uuid),//300点赞
                    'has_like'=>LikeService::hasLike($member_uuid, 5, $value->uuid),//1是已经点like 0是未点like
                    'has_collect'=>isset($collect_arr[$value->uuid]) ? 1 : 0,//1是已经收藏 0是未

                    'longitude'=>$value->longitude,
                    'latitude'=>$value->latitude,
                    'place_city_code'=>$value->place_city_code,//城市code
                    'place'=>$value->place,//位置名
                    'place_address'=>$value->place_address,//位置详细
                    'place_level_1' => $path_names_arr[0] ?? null, //省
                    'place_level_2' => $path_names_arr[1] ?? null, //市
                    'place_level_3' => $path_names_arr[2] ?? null, //区
                    'place_city_name' => $city_arr['name'] ?? null,//城市code

                    'permission'=>$value->permission,// 1关闭+Talking&允许评论，2允许+Talking&关闭评论，3允许+Talking&评论',
                    
                    'tag_struct_obj'=> $tag_struct_obj,
                    'tag_struct'=> !empty($value->tags) ? json_decode($value->tags) : null, 
                    'retweet_comment'=>!empty($value->retweet_comment) ? json_decode($value->retweet_comment) : null,
                    'retweet_info'=>$retweet_info,
                ]
        ];
        return $data;
    }
    /**
     * 返回某条feed 被删除的结构
     * 
     **/
    public static function detailDelStruct($value = null, $member_uuid = ''){
        
        if(empty($value)){
            
            $data = [
                    'user'=> null,
                    'info'=>[
                        'id'=>$value->id ?? null,//信息id
                        'uuid'=>$value->uuid ?? null,//信息uuid
                        'ad'=>0,//1是0不是
                        'type'=>$value->retweet_uuid ?? null,//retweet转发 feed非转发
                        'add_time'=>$value->created_at ?? null,//发布时间
                        'detail'=>'抱歉，该内容已被删除',//内容文字 @人格式：@赵灵儿@
                        'file_list'=>null,//一个资源列表
                        'file_type'=>null,//video 视频或者video 图片
                        'comment_count'=>null,//评论量
                        
                        'like_count'=>null,//300点赞
                        'has_like'=>null,//1是已经点like 0是未点like
                        
                        'longitude'=>null,
                        'latitude'=>null,
                        'place_city_code'=>null,//城市code
                        'place'=>null,//位置名
                        'place_level_1' => null, //省
                        'place_level_2' => null, //市
                        'place_level_3' => null, //区
                        'place_city_name' => null,//城市code

                        'permission'=>null,// 1关闭+Talking&允许评论，2允许+Talking&关闭评论，3允许+Talking&评论',
                        
                        'tag_struct'=> null, 
                        'retweet_comment'=>null,
                        'retweet_info'=>null,
                    ]
            ];
        }
        return $data;
    }

    /**
     * 活动的结构
     **/
    public static function activity(string $uuid = '', string $member_uuid = ''){
        return ActivityService::feedShow($uuid, $member_uuid);
    }

    /**
     * feed的结构
     **/
    public static function feed(string $uuid = '', string $member_uuid = ''){

        // $cache_key = config('cache.key_list.feed_detail').md5($uuid.$member_uuid);
        // $cache_data = Cache::get($cache_key);
        // if(!empty($cache_data)){
        //     return $cache_data;
        // }
        $res = self::detail($uuid);
        $data = self::detailStruct($res, $member_uuid);
        // Cache::put($cache_key, $data, config('cache.ttl'));

        return $data;
    }

    /**
     * vote的结构
     **/
    public static function vote(string $uuid = '', string $member_uuid = ''){

        $where[] = ['uuid', '=', $uuid];
        $data = VoteService::feedVoteInfo($where, $member_uuid);
        return $data;
    }

    /**
     * store的结构
     **/
    public static function store(string $uuid = '', string $member_uuid = ''){

        $where[] = ['uuid', '=', $uuid];
        $data = Store::with('tag')->where($where)->first();
        return $data;
    }

    /**
     * 新闻的结构
     **/
    public static function news(string $uuid = '', string $member_uuid = ''){
        $where[] = ['uuid', '=', $uuid];
        $where[] = ['state', '=', 1];
        $data = News::with('files')->where($where)->first();

        // var_dump($uuid, $member_uuid, $data->toArray());die;
        return $data;
    }


    /**
     * talking的结构
     **/
    public static function talking(string $uuid = '', string $member_uuid = ''){

        $data = TalkingService::talkingDetail($uuid, $member_uuid);
        return $data;
    }

    /**
     * comment
     **/
    public static function comment(string $uuid = '', string $member_uuid = ''){
        $where[] = ['uuid', '=', $uuid];
        $data = Comment::where($where)->first();
        return $data;
    }

    /**
     * 同步信息流
     * feed_param 提交的原信息 
     * $feed_param['circle_perm']; 同步参数
     * $feed_param['service_type']; 业务类型
     * $feed_param['service_uuid']; 业务uuid
     * $feed_param['longitude']; 经
     * $feed_param['latitude']; 纬
     * $feed_param['place_city_code']; 城市code
     * $feed_param['file_type']; 文件类型
     * $feed_param['retweet_type'];
     * $feed_param['target']; //1,2 1自己圈子2学校圈子
     * 
     * $feed_row 已经发布的结果集
     * $feed_row['uuid']; 原业务uuid
     * $feed_row['member_uuid']; 发布者uuid
     * 
     * circle_perm同步信息：{"type":1}
     * type:1同步设定的权限，2仅发布到自己的圈子 
     * 
     * feed_row_arr 写入的信息
     **/
    public static function feedDispatchJob(array $feed_param = [], array $feed_row = []){
        
        //同步学校信息流 学校2
        if($feed_param['target'] == 2){
            $param_school['post_uuid'] = $feed_row['uuid'];
            $param_school['form_member_uuid'] = $feed_row['member_uuid'];
            
            $param_school['school_uuid'] = $feed_param['school_uuid'];
            $param_school['target'] = $feed_param['target'];
            $param_school['state'] = 1; //状态1正常2删除隐藏
            $param_school['target'] = $feed_param['target'];
            $param_school['service_type'] = $feed_param['service_type'] ?? null;
            $param_school['service_uuid'] = $feed_param['service_uuid'] ?? null;
            $param_school['type'] = $feed_param['type'] ?? null;
            $res = FeedViewBySchool::create($param_school);
        }

        //同步圈子
        $circle_perm_arr = [];
        if(isset($feed_param['circle_perm'])){
            $circle_perm_arr = json_decode($feed_param['circle_perm'], true); //同步信息
        }
        if(!isset($circle_perm_arr['type']) || empty($circle_perm_arr['type'])){
            return null;
        }

        $param['type'] = $feed_param['type'] ?? 'feed';//业务类型，可以同步过来的是店铺，活动等
        $param['service_type'] = $feed_param['service_type'] ?? '';//基于某业务类型下发的feed
        $param['service_uuid'] = $feed_param['service_uuid'] ?? '';
        $param['longitude'] = $feed_param['longitude'] ?? '';
        $param['latitude'] = $feed_param['latitude'] ?? '';
        $param['place_city_code'] = $feed_param['place_city_code'] ?? '';
        $param['file_type'] = $feed_param['file_type'] ?? '';
        $param['retweet_type'] = $feed_param['retweet_type'] ?? '';

        //发自己的2 默认就要同步
        $param['post_uuid'] = $feed_row['uuid'];
        $param['member_uuid'] = $feed_row['member_uuid'];
        $param['form_member_uuid'] = $feed_row['member_uuid'];
        $param['target'] = $feed_param['target'];
        $param['state'] = 1; //状态1正常2删除隐藏
        $res = FeedViewByUser::create($param);
        
        //不是同步设定权限就直接返回
        if($circle_perm_arr['type'] != 1){
            return null;
        }
        // 3eaf25a8-47d9-4d00-aca6-89cad29e6a9e
        //取我的分发权限
        $res_hub_set = HubSettings::where('member_uuid',$feed_row['member_uuid'])->first();
        $dispatch_arr = $res_hub_set_data = [];
        if(isset($res_hub_set['data']) || !empty($res_hub_set['data']) ){
            $res_hub_set_data = json_decode($res_hub_set['data'], true);
            $dispatch_arr = $res_hub_set_data['dispatch'];
        }else{
            $dispatch_arr['open'] = 'all';    
        }

        //同步圈主
        if($dispatch_arr['open'] == 'user' ){
            //查出我设置分发的圈子
            $to_uuids = $dispatch_arr['user']['data'];
            //指定圈子
            foreach ($to_uuids as $key => $value) {
                //判断此人是否能接收
                //接收者：value ，发送者：$param['form_member_uuid']
                if(self::checkReceiveByMemberUuid($value, $param['form_member_uuid']) == false){
                    continue;
                }
                $param['member_uuid'] = $value;
                $res = FeedViewByUser::create($param);
            }
        }

        //同步标签
        if($dispatch_arr['open'] == 'tag' ){
            //查出我设置分发标签
            $to_tags = $dispatch_arr['tag']['data'];
            //查出我分发标签的圈主
            $to_uuid = self::getTagMember($to_tags);
            foreach ($to_uuid as $key => $value) {
                //判断此人是否能接收
                if(self::checkReceiveByMemberUuid($value, $param['form_member_uuid']) == false){
                    continue;
                }
                $param['member_uuid'] = $value;
                $res = FeedViewByUser::create($param);
            }
        }

        //同步全部圈子，要查自己加入的全部圈子，自己的全部好友，相互关注
        if($dispatch_arr['open'] == 'all' ){
            //同步全部，但是分发权限不是设置全部
            $frend_list = Friend::where('member_uuid', '=', $feed_row['member_uuid'])->get();
            if(!empty($frend_list)){
                $frend_arr = $frend_list->toArray();
                //自己的全部好友
                foreach ($frend_arr as $key => $value) {
                    $param['member_uuid'] = $value['friend_member_uuid'];
                    //判断此人是否能接收
                    if(self::checkReceiveByMemberUuid($param['member_uuid'], $param['form_member_uuid']) == false){
                        continue;
                    }
                    $res = FeedViewByUser::create($param);
                }
            }
        }

        return $res ? $res : null;
    }

    /**
     * 同步信息流
     * feed_param 提交的原信息 
     * $feed_param['circle_perm']; 同步参数
     * $feed_param['service_type']; 业务类型
     * $feed_param['service_uuid']; 业务uuid
     * $feed_param['longitude']; 经
     * $feed_param['latitude']; 纬
     * $feed_param['place_city_code']; 城市code
     * $feed_param['file_type']; 文件类型
     * $feed_param['retweet_type'];
     * $feed_param['target']; //1,2 1自己圈子2学校圈子
     * 
     * $feed_row 已经发布的结果集
     * $feed_row['uuid']; 原业务uuid
     * $feed_row['member_uuid']; 发布者uuid
     * 
     * circle_perm同步信息：{"type":1}
     * type:1同步设定的权限，2仅发布到自己的圈子 
     * 
     * feed_row_arr 写入的信息
     **/
    public static function feedDispatch(array $feed_param = [], array $feed_row = []){
        $data['feed_param'] = $feed_param;
        $data['feed_row'] = $feed_row;
        \App\Jobs\FeedDispatch::dispatch($data)->onQueue('FeedDispatch');
    }
    
    /**
     * 查某人接收配置情况 
     * form_member_uuid 推给 member_uuid
     * notice:添加时候会判断是否我的好友
     * @param string member_uuid 接收者的uuid
     * @param string form_member_uuid 推送者uuid
     * 能接收返回true，否则false
     **/
    public static function checkReceiveByMemberUuid(string $member_uuid='', string $form_member_uuid=''){
        //如果是禁言。不能同步
        $is_muted = 1;
        if(MemberService::isMyFriend($form_member_uuid, $member_uuid, $is_muted) == true){
            Log::info('禁止同步信息过来'); 
            return false;
        }
        //如果是form_member_uuid拉黑member_uuid。不能同步    aa sync, aa 拉黑 bb
        $is_block = 1;
        if(MemberService::isMyFriendAndBlock($form_member_uuid, $member_uuid, $is_block) == true){
            Log::info('拉黑，A不同步给B'); 
            return false;
        }
        //form_member_uuid 屏蔽 member_uuid 同步的消息 bb sync, aa 拉黑 bb
        $is_block = 1;
        if(MemberService::isMyFriendAndBlock($member_uuid, $form_member_uuid, $is_block) == true){
            Log::info('拉黑，A屏蔽B的同步'); 
            return false;
        }
        
        // $count = Friend::where('member_uuid', '=', $member_uuid)->where('friend_member_uuid','=',$form_member_uuid)->count();
        // //判断是否好友
        // if($count<=0){
        //     return false;
        // }
        // $res_hub_set_data = json_decode($res_hub_set['data'] ?? [], true);

        //查看接收权限
        $res_hub_set = HubSettings::where('member_uuid',$member_uuid)->first();
        if(isset($res_hub_set['data']) || !empty($res_hub_set['data']) ){
            $res_hub_set_data = json_decode($res_hub_set['data'], true);
            $receive_arr = $res_hub_set_data['receive'];
        }else{
            $receive_arr['open'] = 'all';    
        }
        //空默认全接收
        if(empty($res_hub_set_data) || !isset($res_hub_set_data['receive']) || empty($res_hub_set_data['receive']) ){
            return true;
        }
        
        if(!empty($receive_arr)){
            // open
            if($receive_arr['open'] == 'all'){
                return true;
            }
            if($receive_arr['open'] == 'block_all'){
                return false;
            }
            if($receive_arr['open'] == 'block_tag'){
                //查不接收标签组的人, 是否有推送者的uuid
                $tag_member_arr = self::getTagMember($receive_arr['block_tag']['data']);
                if(in_array($form_member_uuid, $tag_member_arr)){
                    return false;
                }
            }
            if($receive_arr['open'] == 'block_user' && in_array($form_member_uuid, $receive_arr['block_user']['data'])){
                return false;
            }
        }
        return true;
    }    

    /**
     * 查出某标签下的用户
     * 
     **/
    public static function getTagMember(array $tag_uuid_data = []){
        $tag_member_res = TagMember::whereIn('tag_uuid',$tag_uuid_data)->get();
        $tag_member_all_arr = [];
        if(!empty($tag_member_res)){
            $tag_member_all_arr = $tag_member_res->toArray();
        }
        return $tag_member_arr = array_column($tag_member_all_arr, 'service_uuid');

    }

    /**
     * 保存用户人个的信息流 
     * 
     **/
    public static function officialToUserFeed(array $param=[]){

        $official_feed_uuid = env('OFFICIAL_FEED_UUID');
        $official_feed_member_uuid = env('OFFICIAL_FEED_MEMBER_UUID');

        if(empty($official_feed_uuid) || empty($official_feed_member_uuid)){
            return null;
        }

        //自己的
        $param['member_uuid'] = $param['member_uuid'];
        $param['post_uuid'] = $official_feed_uuid; //官方用户指定流uuid
        $param['form_member_uuid'] = $official_feed_member_uuid;//官方用户uuid
        $param['target'] = 1;
        $param['state'] = 1; //状态1正常2删除隐藏
        $res = FeedViewByUser::create($param);
        return $res ? $res : null;
    }

    /**
     * 保存feed
     * $member_uuid 当前登录用户的uuid
     * 
     **/
    public static function saveFeed(array $param=[], string $member_uuid = ''){
        $tag_uuid = '55088298-5945-49b5-8743-811f5e0d39a4'; //tag 默认一种分类，推文专用，便于扩展
        $param_disp = $param;
        unset($param['school_uuid']);
        
        if(!empty($param['longitude']) && !empty($param['latitude'])){
            $location = $param['longitude'].','.$param['latitude'];
            $regeo_str = UtilService::getRegeo($location);
            $param['place_address'] = $regeo_str;
        }
        //发布推文
        $res = Feeds::create($param);
        $feed_row_arr = $res->toArray();

        //图片文件批量写入，如果传来的是数组
        //$file['path'], $file['size'], $file['height'], $file['width']
        if($param['file_type'] == 'image'){
            $file_list_arr = json_decode($param['file_list'], true);
            
            foreach ($file_list_arr as $file) {
                if(is_array($file)){
                    $fileData = [
                        'service_id' => $feed_row_arr['uuid'],
                        'place' => 'feed',
                        'path' => $file['path'],
                        'type' => '1',
                        'size' => $file['size'] ?? '',
                        'height' => $file['height'] ?? '',
                        'width' => $file['width'] ?? '',
                        'sort' => 0,
                    ];

                    File::create($fileData);
                }
            }
        }

        //发布时候的标签
        
        if(isset($param['tags'])){
            $param_tags_arr = json_decode($param['tags'], true);
            if(!empty($param_tags_arr)){
                foreach ($param_tags_arr as $key => $value) {
                    $param_tags['type'] = $tag_uuid;
                    $param_tags['state'] = 1;
                    $param_tags['title'] = $value;
                    $param_tags['post_uuid'] = $feed_row_arr['uuid'];
                    $param_tags['member_uuid'] = $member_uuid;
                    $row = FeedsService::saveFeedTags($param_tags);
                }            
            }
        }

        //@用户通知
        //php artisan make:job NotifyUsers
        if(isset($param['notify_users'])){
            $notify_users_arr = json_decode($param['notify_users']);
            $notify_users_Job = [];
            if(!empty($notify_users_arr)){
                foreach ($notify_users_arr as $key => $value) {
                    $notify_users_Job[] =[  'form_member_uuid'=> $member_uuid,
                                            'member_uuid'=> $value, 
                                            'post_uuid'=>$feed_row_arr['uuid']
                                        ];
                }
                \App\Jobs\NotifyUsers::dispatch($notify_users_Job)->onQueue('NotifyUsers');
            }
        }

        self::feedDispatch($param_disp, $res->toArray());

        return $res ? $res : null;
    }

    public static function saveFeedTags(array $param=[]){

        $res = FeedsTags::firstOrCreate(['title'=>$param['title']],$param);
        return $res ? $res : null;
    }

}